package com.swang.framework.core.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * @ClassName: NumberUtil
 * @Description: 数字转换工具
 * @author swang@swang.com
 * @date 2017年3月16日 下午9:45:51
 */
public class NumberUtil {

    private static final BigDecimal TEN_THOUSAND        = new BigDecimal(10000L);     // 1万

    private static final BigDecimal ONE_HUNDRED_MILLION = new BigDecimal(100000000L); // 1亿

    public static String formatValue(long number) {
        BigDecimal decimal = new BigDecimal(number);
        if (decimal.compareTo(TEN_THOUSAND) < 0) {
            return String.valueOf(number);
        } else if (decimal.compareTo(ONE_HUNDRED_MILLION) < 0) {
            BigDecimal val = decimal.divide(TEN_THOUSAND);
            return formatByCeiling(val, 1) + "万";
        } else {
            BigDecimal val = decimal.divide(ONE_HUNDRED_MILLION);
            return formatByCeiling(val, 1) + "亿";
        }
    }

    public static String formatByHalfUp(BigDecimal target, int digits) {
        return format(target, digits, RoundingMode.HALF_UP);
    }

    public static String formatByCeiling(BigDecimal target, int digits) {
        return format(target, digits, RoundingMode.CEILING);
    }

    public static String format(BigDecimal target, int digits, RoundingMode mode) {
        StringBuilder pattern = new StringBuilder("0.");
        for (int i = 0; i < digits; i++) {
            pattern.append("0");
        }
        DecimalFormat df = new DecimalFormat(pattern.toString());
        df.setRoundingMode(mode);
        return df.format(target);
    }

    public static void main(String[] args) {
        System.out.println(formatValue(19001L)); // 2.0万
        System.out.println(formatValue(10001L)); // 1.1万
    }

}
